import java.lang.management.ManagementFactory
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

/**
 * 编译器性能监控器
 * 负责收集和分析不同编译器环境下的性能数据
 */
object CompilerPerformanceMonitor {
    // 性能指标存储
    private val metrics = ConcurrentHashMap<String, AtomicLong>()
    private val startTime = System.nanoTime()
    private var isRunning = false
    
    /**
     * 启动性能监控
     */
    fun startMonitoring() {
        if (isRunning) return
        
        isRunning = true
        println("启动编译器性能监控...")
        
        // 启动定期报告线程
        thread(name = "CompilerPerformanceMonitor") { runPerformanceMonitoring() }
        
        // 注册JVM钩子
        Runtime.getRuntime().addShutdownHook(thread(start = false) { stopMonitoring() })
    }
    
    /**
     * 停止性能监控
     */
    fun stopMonitoring() {
        if (!isRunning) return
        
        isRunning = false
        println("停止编译器性能监控...")
        
        // 输出最终报告
        generateFinalReport()
    }
    
    /**
     * 记录方法执行时间
     */
    fun recordExecutionTime(methodName: String, executionTimeNanos: Long) {
        metrics.computeIfAbsent("method.$methodName.time", { AtomicLong(0) }).addAndGet(executionTimeNanos)
        metrics.computeIfAbsent("method.$methodName.count", { AtomicLong(0) }).incrementAndGet()
    }
    
    /**
     * 记录内存使用
     */
    fun recordMemoryUsage(bytes: Long) {
        metrics.computeIfAbsent("memory.used", { AtomicLong(0) }).addAndGet(bytes)
        metrics.computeIfAbsent("memory.count", { AtomicLong(0) }).incrementAndGet()
    }
    
    /**
     * 记录编译事件
     */
    fun recordCompilationEvent(compiler: String, method: String, isOptimized: Boolean) {
        val key = if (isOptimized) "compilation.$compiler.optimized" else "compilation.$compiler.normal"
        metrics.computeIfAbsent(key, { AtomicLong(0) }).incrementAndGet()
        metrics.computeIfAbsent("compilation.$method", { AtomicLong(0) }).incrementAndGet()
    }
    
    /**
     * 性能监控主循环
     */
    private fun runPerformanceMonitoring() {
        try {
            while (isRunning) {
                Thread.sleep(60000) // 每分钟报告一次
                generatePerformanceReport()
            }
        } catch (e: InterruptedException) {
            Thread.currentThread().interrupt()
        }
    }
    
    /**
     * 生成性能报告
     */
    private fun generatePerformanceReport() {
        val runtimeMXBean = ManagementFactory.getRuntimeMXBean()
        val osMXBean = ManagementFactory.getOperatingSystemMXBean()
        val memoryMXBean = ManagementFactory.getMemoryMXBean()
        
        val uptime = TimeUnit.MILLISECONDS.toSeconds(runtimeMXBean.uptime)
        val heapMemoryUsed = memoryMXBean.heapMemoryUsage.used / (1024 * 1024)
        val nonHeapMemoryUsed = memoryMXBean.nonHeapMemoryUsage.used / (1024 * 1024)
        val systemLoad = (osMXBean as com.sun.management.OperatingSystemMXBean).systemLoadAverage
        
        println("\n===== KUYA 性能报告 (运行时间: ${uptime}s) =====")
        println("系统负载: $systemLoad")
        println("堆内存使用: ${heapMemoryUsed}MB")
        println("非堆内存使用: ${nonHeapMemoryUsed}MB")
        
        // 输出方法执行统计
        metrics.entries.filter { it.key.startsWith("method.") && it.key.endsWith(".time") }
            .forEach { (key, value) ->
                val methodName = key.substring(7, key.length - 5)
                val count = metrics["method.$methodName.count"]?.get() ?: 0
                if (count > 0) {
                    val avgTimeNanos = value.get() / count
                    val avgTimeMs = avgTimeNanos / 1_000_000.0
                    println("方法 '$methodName': 执行 $count 次, 平均耗时: %.3f ms".format(avgTimeMs))
                }
            }
        
        // 输出编译统计
        metrics.entries.filter { it.key.startsWith("compilation.") }
            .forEach { (key, value) ->
                if (!key.contains(".")) {
                    println("$key: ${value.get()} 次")
                }
            }
        println("==========================================\n")
    }
    
    /**
     * 生成最终性能报告
     */
    private fun generateFinalReport() {
        println("\n===== KUYA 最终性能报告 =====")
        val totalRuntime = (System.nanoTime() - startTime) / 1_000_000_000.0
        println("总运行时间: %.2f 秒".format(totalRuntime))
        generatePerformanceReport()
    }
}